package callchain.lightcallgraph;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class LightCallGraph {
	private Map<Integer, List<Integer>> index2tgts;
	
	public LightCallGraph(){
		index2tgts = new HashMap<Integer, List<Integer>>();
	}
	
	public void addArc(Integer srcNodeIndex, Integer tgtNodeIndex){
		List<Integer> currentTgts = index2tgts.get(srcNodeIndex);
		if( currentTgts == null ){
			currentTgts = new ArrayList<Integer>();
			currentTgts.add(tgtNodeIndex);
			index2tgts.put(srcNodeIndex, currentTgts);
		}else{
			if(!currentTgts.contains(tgtNodeIndex)){
				currentTgts.add(tgtNodeIndex);
			}
		}
	}
	
	public List<Integer> getTargets(Integer srcNodeIndex){
		return index2tgts.get(srcNodeIndex);
	}
	
	public String toString(){
		StringBuilder cgStr = new StringBuilder();
		Set<Integer> keySet = index2tgts.keySet();
		for(Integer currentKey : keySet){
			cgStr.append(currentKey);
			cgStr.append("-->");
			cgStr.append(index2tgts.get(currentKey));
			cgStr.append("\n");
		}
		
		return cgStr.toString();
	}
	
	public void storeGraph(String fileName){
		File graphFile = new File(fileName);
		try {
			PrintWriter pw = new PrintWriter(graphFile);
			StringBuilder cgStr = new StringBuilder();
			Set<Entry<Integer, List<Integer>>> entrySet = index2tgts.entrySet();
			for(Entry<Integer, List<Integer>> currentEntry : entrySet){
				Integer currentKey = currentEntry.getKey();
				List<Integer> currentValue = currentEntry.getValue();
				
				if(currentValue == null || currentValue.size() == 0){
					continue;
				}else{
					cgStr.append(currentKey);
					cgStr.append("-->");
					for(Integer tmpTgt : currentValue){
						cgStr.append(tmpTgt);
						cgStr.append(",");
					}
					cgStr.append("\n");
				}
			}
			pw.print(cgStr.toString());
			pw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
